package com.ghostflying.cameraonfly;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class UDPservice {
        private static boolean DEBUG=true;
        private static String TAG="UDP"; 
        
        private receiveThread mreceiveThread = null;
        private DatagramSocket mDatagramSocket = null;
        private sendThread msendThread = null;
        
        private final Handler mHandler;
        
        public UDPservice(Context context,Handler handler){
                mHandler=handler;
        }
        
        public boolean startListen(int port){
                try {
                        mDatagramSocket = new DatagramSocket(port);
                } catch (SocketException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                mreceiveThread = new receiveThread(mDatagramSocket);
                mreceiveThread.start();
                return true;            
        }
        

        
        
        public boolean write(byte[] send,String ipadd,int port){
                if (msendThread == null){
                        msendThread = new sendThread(send,ipadd,port);
                        msendThread.start();
                        return true;
                }
                else if (msendThread.getState()!= Thread.State.RUNNABLE){
                        msendThread = new sendThread(send,ipadd,port);
                        msendThread.start();
                        return true;
                }
                return false;           
        }
        
        private class sendThread extends Thread{
                DatagramSocket mDatagramSocket = null;
                int length = 0;
                byte[] out;
                String ip;
                int mport;
                
                public sendThread(byte[] send,String ipadd,int port){
                        ip = ipadd;
                        mport = port;
                        out = send;
                        length = send.length;
                }

                
                public void run(){              
                        try {
                                mDatagramSocket = new DatagramSocket();
                                DatagramPacket p = new DatagramPacket(out,length,InetAddress.getByName(ip),mport);
                                mDatagramSocket.send(p);
                        } catch (SocketException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (UnknownHostException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        
                }
                

        }
        
        private class receiveThread extends Thread{
                private DatagramSocket mDatagramSocket=null;
                private DatagramPacket mDatagramPacket=null;
                private DatagramPacket mmDatagramPacket=null;
                private byte[] message;
                private byte[] messagelength;
                private int length = 0;
                public receiveThread(DatagramSocket datagramSocket){
                        mDatagramSocket=datagramSocket;
                        messagelength = new byte [4];
                        mmDatagramPacket = new DatagramPacket (messagelength,messagelength.length);
                }
                public void run(){
                        while (true){
                                try {
                                        mDatagramSocket.receive(mmDatagramPacket);
                                        length = b2i(mmDatagramPacket.getData());
                                        message = new byte[length];
                                        mDatagramPacket = new DatagramPacket(message,message.length);
                                        mDatagramSocket.receive(mDatagramPacket);
/*                                      FileOutputStream outStream = null;
                                        outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
                                        outStream.write(message,0, length);
                                        outStream.close();*/
                                        if (DEBUG){
                                                Log.d(TAG,Integer.toString(length));
                                        }
                                        //mHandler.obtainMessage(MainActivity.MESSAGE_BYTE, length, -1, message).sendToTarget();
                                } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                                
                        }
                }

        }
        
    private int b2i(byte[] b) {   
        int value = 0;   
        for (int i = 0; i < 4; i++) {   
            int shift = (4 - 1 - i) * 8;   
            value += (b[i] & 0x000000FF) << shift;   
        }   
        return value;   
    } 
        
}